package com.sjb.sixteen_journey_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sjb.sixteen_journey_backend.common.CommonHandle;
import com.sjb.sixteen_journey_backend.common.R;
import com.sjb.sixteen_journey_backend.entity.Comment;
import com.sjb.sixteen_journey_backend.entity.Message;
import com.sjb.sixteen_journey_backend.entity.User;
import com.sjb.sixteen_journey_backend.entity.dto.CommentDto;
import com.sjb.sixteen_journey_backend.entity.vo.UserBaseMsgVo;
import com.sjb.sixteen_journey_backend.mapper.CommentMapper;
import com.sjb.sixteen_journey_backend.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjb.sixteen_journey_backend.service.IMessageService;
import com.sjb.sixteen_journey_backend.service.IUserService;
import com.sjb.sixteen_journey_backend.utils.ThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.time.LocalTime.now;

/**
 * <p>
 * 评论列表 服务实现类
 * </p>
 *
 * @author jcz
 * @since 2024-07-23
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {


    @Autowired
    private IUserService userService;

    @Autowired
    private IMessageService messageService;

    @Autowired
    private CommonHandle commonHandle;
    @Override
    public R addComment(CommentDto commentDto) {
        try {
            if(!commonHandle.determineIsExistTicket(commentDto.getModuleStatus(),commentDto.getModuleId())){
                return R.error("该文不存在");
            }
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            Comment comment = new Comment();
            BeanUtils.copyProperties(commentDto,comment);
            comment.setUserId(userId);
            if(commentDto.getParentsId() != null){
                comment.setParentsId(this.getById(commentDto.getParentsId()).getCommentId());
                comment.setTargetId(this.getById(commentDto.getParentsId()).getUserId());
            }
            if (this.save(comment)) {
                Message message = new Message();
                message.setCommentId(comment.getCommentId());
                message.setUserId(comment.getUserId());
                message.setTargetId(comment.getTargetId());
                message.setPostdate(comment.getPostdate());
                messageService.save(message);
                return R.success(null,"评论成功");
            }
            return R.error("评论失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R showComment(Integer statusId, Integer moduleId) {
        try {
            if(!commonHandle.determineIsExistTicket(statusId,moduleId)){
                return R.error("该文不存在");
            }
            QueryWrapper<Comment> wrapper = Wrappers.query();
            wrapper.eq("module_status",statusId);
            wrapper.eq("module_id",moduleId);
            List<Comment> comments = this.list(wrapper);
            for(Comment comment:comments){
                User user = userService.getById(comment.getUserId());
                UserBaseMsgVo userBaseMsgVo = new UserBaseMsgVo();
                BeanUtils.copyProperties(user,userBaseMsgVo);
                comment.setUser(userBaseMsgVo);
                if(comment.getTargetId()!=null){
                    user=userService.getById(comment.getTargetId());
                    userBaseMsgVo = new UserBaseMsgVo();
                    BeanUtils.copyProperties(user,userBaseMsgVo);
                    comment.setTargetUser(userBaseMsgVo);
                }
            }
            List<Comment> rootComments = comments.stream().filter(comment -> comment.getParentsId() == null).collect(Collectors.toList());
            // 按照时间postdate离现在最近的顺序排列rootComments
            rootComments.sort((c1, c2) -> c2.getPostdate().compareTo(c1.getPostdate()));
            for(Comment rootComment : rootComments){
                rootComment.setChildren(comments.stream().filter(comment ->  rootComment.getCommentId().equals(comment.getParentsId())).collect(Collectors.toList()));
            }
            return R.success(rootComments,"获取评论成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R deleteComment(Integer commentId) {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            Comment comment = this.getById(commentId);
            if(userId.equals(comment.getUserId())){
                //当此评论为用户自己发的评论时才可以删除
                if(this.removeById(commentId)){
                    return R.success(null,"删除成功");
                }
            }
            return R.error("删除失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
